package com.compmov.socialnetwork;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.compmov.datamodel.Lugar;
import com.compmov.datamodel.TipoLugar;
import com.compmov.webservice.TipoLugarWSClient;
import com.compmov.webservice.LugarWSClient;
import com.compmov.webservice.WSClientException;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Maps extends MapActivity 
{    
	public static final String TAG ="WEBSERVICE";
	int id;

	MapView mapView; 
	LinearLayout linearLayout;
	List<Overlay> mapOverlays;
	Drawable drawable;
	MyItemizedOverlay itemizedOverlay;	

	private LocationManager myLocationManager;
	private LocationListener myLocationListener;
	OverlayItem currentOverlay;
	private MapController myMapController;

	GeoPoint initGeoPoint;

	private List<TipoLugar> tipoLugares;
	private String[] tiposLugares;
	private List<Lugar> lugares;

	private void CenterLocation(GeoPoint centerGeoPoint)
	{
		initGeoPoint=centerGeoPoint;
		if (itemizedOverlay != null)
			itemizedOverlay.removeOverlay(currentOverlay);

		currentOverlay = new OverlayItem(centerGeoPoint, "", "");
		itemizedOverlay.addOverlay(0,currentOverlay);
		itemizedOverlay.addOverlayPlace(0, null);
		mapOverlays.add(itemizedOverlay);
		myMapController.animateTo(centerGeoPoint);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_map);

		Bundle extras = getIntent().getExtras();
		id= Integer.valueOf(extras.getString("id"));

		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);

		mapOverlays = mapView.getOverlays();
		drawable = this.getResources().getDrawable(R.drawable.androidmarker);
		itemizedOverlay = new MyItemizedOverlay(this,drawable,mapView);

		myMapController = mapView.getController();
		myMapController.setZoom(15); //Fixed Zoom Level

		myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		myLocationListener = new MyLocationListener();
		myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				200L, 50.0f, myLocationListener);
		//Para la Red inalambrica
		myLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 200L, 50.0f, myLocationListener);

		//Get the current location in start-up


		initGeoPoint = getLocation();
		/*GeoPoint initGeoPoint = new GeoPoint(
				(int)(myLocationManager.getLastKnownLocation(
						LocationManager.GPS_PROVIDER)
						.getLatitude()*1000000),
						(int)(myLocationManager.getLastKnownLocation(
								LocationManager.GPS_PROVIDER)
								.getLongitude()*1000000));*/
		if(initGeoPoint!=null)
			CenterLocation(initGeoPoint);

	}	

	//Se obtienen la ubicacion
	private GeoPoint getLocation() {
		GeoPoint initGeoPoint = null;		
		// se obtiene la ultima ubicacion del proveedor de red
		Location location = myLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		//es null?
		if (location == null) {
			//se obtiene la ultima ubicacion de gps
			location = myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		}
		if (location != null) {
			initGeoPoint = new GeoPoint(
					(int)(location.getLatitude()*1000000),
					(int)(location.getLongitude()*1000000));
		} 
		return initGeoPoint;
	}

	private class MyLocationListener implements LocationListener{

		public void onLocationChanged(Location argLocation) {
			// TODO Auto-generated method stub
			GeoPoint myGeoPoint = new GeoPoint(
					(int)(argLocation.getLatitude()*1000000),
					(int)(argLocation.getLongitude()*1000000));

			CenterLocation(myGeoPoint);
		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onStatusChanged(String provider,
				int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
	}

	public void showPerfil(View v){
		Intent nuevoIntent = new Intent(this.getApplicationContext(),
				Perfil.class);					
		startActivity(nuevoIntent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);
		return true;
	}

	//  @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		Intent intent;
		switch (item.getItemId()) {
		case R.id.itmBuscar:
			itemizedOverlay.removeOverlays();

			getTipoLugares();
			intent = new Intent(this.getApplicationContext(),Buscar.class);  
			intent.putExtra("tipo", tiposLugares);
			startActivityForResult(intent,  0);
			return true;
		case R.id.itmAgregar:
			Intent nuevoIntent = new Intent(getApplicationContext(), Agregar.class);
			startActivityForResult(nuevoIntent,0);	
			return true;
		case R.id.itmLogOut:
			intent = new Intent(this.getApplicationContext(),Main.class);
			startActivity(intent);
			finish();
			return true;
		case R.id.itmExit:
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 0:
			if(resultCode==RESULT_OK){	

				TipoLugar tipo= new TipoLugar();
				Bundle extras = data.getExtras();
				int num=Integer.valueOf(extras.getString("tipo"));
				if(num!=0)
					tipo= tipoLugares.get(num-1);					
				Lugar lugar=new Lugar(extras.getString("nombre"), tipo);
				boolean sugerido=Boolean.valueOf(extras.getString("sugerido"));
				Double lat=0.0;
				Double lon=0.0;
				if(Boolean.valueOf(extras.getString("posicion"))){
					lat=(double)initGeoPoint.getLatitudeE6()/1000000;
					lon=(double)initGeoPoint.getLongitudeE6()/1000000;
				}

				int ranking=Integer.valueOf(extras.getString("ranking"));
				if (ranking!=0)
					ranking=6-ranking;

				Log.d(TAG,extras.getString("nombre"));
				Log.d(TAG,lugar.getNombre());
				Log.d(TAG,extras.getString("tipo"));
				Log.d(TAG,extras.getString("sugeridos"));		
				Log.d(TAG,lat.toString());		
				Log.d(TAG,lon.toString());		
				Log.d(TAG,String.valueOf(ranking));	
				getLugares(lugar, sugerido, ranking, lat, lon, id);
				int i=0;
				for (Lugar l : lugares){ 
					int latitud=(int)(l.getLatitud()*1000000);
					int longitud=(int)(l.getLongitud()*1000000);
					GeoPoint point = new GeoPoint(latitud, longitud);
					OverlayItem overlayitem = new OverlayItem(point, "", "");	
					itemizedOverlay.addOverlay(overlayitem);
					itemizedOverlay.addOverlayPlace(l);
					i++;					
				}
				mapOverlays.add(itemizedOverlay);



			}
			break;
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public void getTipoLugares(){
		try {
			TipoLugarWSClient tipoLugarWS = new TipoLugarWSClient("tipolugar"); 
			tipoLugares = tipoLugarWS.getAll();
			tiposLugares = new String[tipoLugares.size()+1];			
			tiposLugares[0] = "Todos";
			int i=1;
			for (TipoLugar tl : tipoLugares){
				tiposLugares[i] = tl.getDescripcion();				
				i++;
			}
		} catch (WSClientException e) {
			// TODO Auto-generated catch block		
			Log.d(TAG,e.getMessage());			
		}

	}
	public void getLugares(Lugar lugarFiltro, Boolean sugerido, Integer ranking, Double latitude, Double longitude, Integer ide_per){

		try {
			LugarWSClient tipoLugarWS = new LugarWSClient("lugar"); 
			lugares = tipoLugarWS.buscarLugar(lugarFiltro, sugerido, ranking, latitude, longitude, ide_per);

		} catch (WSClientException e) {
			// TODO Auto-generated catch block		
			Log.d(TAG,e.getMessage());			
		}

	}
}